<template>
    <div class="container" v-loading="isLoading">
        <div class="play-back-tree">
            <div class="video-tree-input">
                <el-input v-model="monitorSearchValue" placeholder="搜索监控通道"></el-input><el-button style="margin-left:20px" @click="search" type="primary">搜索</el-button>
            </div>
            <div class="monitor-ul">
                <div @click="monitorBtn(item)" :class="channel_no == item.channel_no ? 'monitor-item-active':'monitor-item'" v-for="(item, $index) in monitorList" :key="this">{{item.name}}</div>
            </div>
        </div>
        <div class="play-back-list">
            <div class="play-back-list-main">
                <div class="select-input">
                    <span class="select-type">
                        锁定类型：
                        <el-select v-model="lockType" placeholder="请选择锁定类型">
                            <el-option label="全部" value="shanghai"></el-option>
                            <el-option label="已锁定" value="shanghai"></el-option>
                            <el-option label="未锁定" value="beijing"></el-option>
                        </el-select>
                    </span>
                    <el-date-picker
                        class="time-input"
                        v-model="playBackTime"
                        type="daterange"
                        align="right"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"
                        @change="changeBackTime">
                    </el-date-picker>
                    <el-button type="primary" @click="queryBtn">查询</el-button>
                </div>
                <v-empty :value="playList"></v-empty>
                <div class="play-back-ul">
                    <el-collapse v-model="activeNames" accordion>
                        <el-collapse-item v-for="(item, $index) in playList" :name="$index" :key="$index">
                            <template slot="title">
                                <div class="play-back-li-date"><span>{{$index}}</span></div>
                            </template>
                            <div class="back-list">
                                <span class="back-li" @click="monitorCheck(site)" v-for="(site, $playIndex) in item" :key="$playIndex">
                                    <div class="li-video">
                                        <i class="el-icon-video-play"></i>
                                    </div>
                                    <div class="video-time">{{common.formatHMS_min(site.startTime/1000)}}~{{common.formatHMS_min(site.endTime/1000)}}</div>
                                </span>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </div>
            <div class="monitor" v-show="isShow">
                <div class="monitor-video" ref="playbackmonitor0" id="playbackmonitor0"></div>
                <i class="el-icon-close" @click="closeMonitor"></i>
            </div>
        </div>
    </div>
</template>
<script>
    import dayjs from 'dayjs';
    import empty from '../../../components/empty.vue';
    import EZUIKit from 'ezuikit-js';
    export default {
        components: {
            'v-empty': empty
        },
        props: {
            name: {
                type: String
            }
        },
        data() {
            return {
                isLoading: false,
                monitorSearchValue: '',
                monitorTotalList: [],
                monitorList: [],
                channel_no: '',
                device: '',
                playBackTime: [],
                playList: '',
                isShow: false,
                activeNames: [],
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now() - 8.64e6;
                    }
                },
                player: null,
                beginTime: null,
                endTime: null,
                currentTime: 0,
                playBackVideo: null,
                timeDiff: 0,
                duration: "00:00",
                initialTime: "00:00",
                touchValue: 0,
                isPlay: false,
                monitorLoading: false,
                token: ''
            }
        },
        watch: {
            'name': function() {
                if(this.name === 'first') {
                    // this.isShow = false;
                    // if(this.player != null) {
                    //     this.player.dispose();
                    //     this.player = null;
                    // }
                }
            }
        },
        created() {
            // this.isLoading = true;
            this.$nextTick(() => {
                this.playBackVideo = document.getElementById('playBack');
            })
            // 监控点列表
            let monitor = this.$http.get('/api/v1/security/monitor')
            .then((res) => {
                if(res.data) {
                    this.token = res.access_token;
                    this.monitorList = res.data.slice(0, 5);
                    this.monitorTotalList = res.data;
                }
            })
            .catch(() => {})
            // let token = this.$http.get('/api/v1/monitor/access_token').then((res) => {
            //     this.token = res.data.token;
            // }).catch(() => {})
            // this.isLoading = true;
            // this.$http.requestAll([monitor])
            // .then(() => {
            //     this.isLoading = false;
            // })
        },
        mounted() {
            // let _this = this;
            // window.onresize = function() {
            //     if(_this.$route.path === '/Security/VideoMonitoring' && _this.name ==='second') {
            //         if(_this.isShow) {
            //             let height1 = _this.$refs.monitor0.offsetHeight;
            //             let width1 = _this.$refs.monitor0.offsetWidth;
            //             if(width1 >=parseInt(height1 / 0.5625)) width1 = parseInt(height1 / 0.5625);
            //             if(_this.player) _this.player.reSize(width1, height1);
            //         }
            //     }
            // }
        },
        methods: {
            // 搜索
            search() {
                if(this.monitorSearchValue) {
                    let arr = [];
                    this.monitorTotalList.forEach((v, i) => {
                        if(v.name.indexOf(this.monitorSearchValue) != -1) {
                            arr.push(v);
                        }
                    })
                    this.monitorList = arr;
                }else {
                    this.monitorList = JSON.parse(JSON.stringify(this.monitorTotalList));
                }
            },
            monitorBtn(item) {
                this.channel_no = item.channel_no;
                this.device = item.device;
                if(this.playBackTime && this.playBackTime.length == 2) {
                    this.requestFun();
                }else {
                    this.$message.warning('请选择查看时间范围');
                }
            },
            requestFun() {
                this.isLoading = true;
                this.isShow = false;
                this.activeNames = [];
                let start_time = this.common.YMD(Date.parse(this.playBackTime[0])/1000)+ ' 00:00:00';
                let end_time = this.common.YMD(Date.parse(this.playBackTime[1])/1000)+ ' 23:59:59';
                this.$http.get(`/api/v1/security/monitor_playback?start_time=${Date.parse(start_time)}&end_time=${Date.parse(end_time)}&channelNo=${this.channel_no}&deviceSerial=${this.device}`)
                .then((res) => {
                    this.isLoading = false;
                    let obj = {};
                    if(res.data) {
                        res.data.forEach((v) => {
                            if(obj[this.common.YMD(v.startTime/1000)]) {
                                obj[this.common.YMD(v.startTime/1000)].push(v);
                            }else {
                                obj[this.common.YMD(v.startTime/1000)] = [v];
                            }
                        })
                    }
                    this.playList = obj;
                })
                .catch(() => {
                    this.isLoading = false;
                })
            },
            timeUpdatethree(val){
                let sTime=new Date(val[0]).getTime();
                let eTime=new Date(val[1]).getTime() + 86399;
                let reduceDate=(eTime-sTime)/1000/60/60/24;
                if(reduceDate>15){
                    return true;
                }
            },
            changeBackTime(val) {
                if(val!=null){
                    if(this.timeUpdatethree(val)){
                        this.$message.warning('查询天数不能大于15天');
                        this.playBackTime = [];
                    }
                }
            },
            queryBtn() {
                if(!this.playBackTime || this.playBackTime.length < 2) {
                    this.$message.warning('请选择查看时间范围');
                    return false;
                }
                if(!this.channel_no) {
                    this.$message.warning('请选择监控点');
                    return false;
                }
                if(this.playBackTime && this.playBackTime.length == 2 && this.channel_no) {
                    this.requestFun();
                }
            },
            // 播放
            videoPlayBtn() {
                this.isPlay = true;
                this.startPlay(document.getElementById('playBack'));
            },
            // 暂停
            videoPauseBtn() {
                this.isPlay = false;
                this.touchValue = this.currentTime;
                if(this.player) this.pausemix(this.player);
            },
            currentTimeChange(val) {
                if(val >= this.timeDiff) {
                    this.touchValue = 0;
                    this.currentTime = 0;
                    this.initialTime = '00:00';
                    this.isPlay = false;
                    if(this.player) {
                        this.pausemix(this.player);
                    }
                }else {
                    this.touchValue = val;
                    this.currentTime = parseInt(val);
                    if(this.player) {
                        this.pausemix(this.player);
                    }
                    this.initialTime = this.common.formatDuring(parseInt(val) * 1000);
                    this.startPlay(document.getElementById('playBack'));
                }
            },
            startPlay(centeredVideo) {
                let t = dayjs(new Date(this.beginTime).getTime() + (parseInt(this.currentTime) * 1000)).format();
                let index= t.lastIndexOf("\+");
                let index1= this.endTime.lastIndexOf("\.");
                let beginTime = t.substring(0, index).replace(/-/g,"").replace(/:/g,"");
                let endTime = this.endTime.substring(0, index1).replace(/-/g,"").replace(/:/g,"");
                this.player = this.initFlvPlayer(centeredVideo, `${this.channel_no}&start_time=${beginTime}&end_time=${endTime}`);
            },
            timeupdateChange(e) {
                if(!this.isPlay) {       //暂停

                }else {
                    this.initialTime = this.common.formatDuring((parseInt(this.touchValue) + parseInt(e.target.currentTime)) * 1000);
                    this.currentTime = parseInt(this.touchValue) + parseInt(e.target.currentTime);
                    if(this.currentTime >= this.timeDiff) {
                        this.isPlay = false;
                        this.touchValue = 0;
                        this.currentTime = 0;
                        this.initialTime = '00:00';
                    }
                }
            },
            // 初始化视频流
            initFlvPlayer() {
                var myVideoDiv = document.getElementById('playbackmonitor0');
                var tagName = document.createElement('div');
                tagName.className = 'video-js vjs-default-skin vjs-big-play-centered';
                tagName.setAttribute('id', 'monitorVideo');
                myVideoDiv.appendChild(tagName);
                let height = document.getElementById(`monitorVideo`).offsetHeight;
                let width = document.getElementById(`monitorVideo`).offsetWidth;
                if(width >=parseInt(height / 0.5625)) width = parseInt(height / 0.5625);
                var player =  new EZUIKit.EZUIKitPlayer({
                    autoplay: true,
                    id: 'monitorVideo',
                    accessToken: 'at.aeaywn60bgduk5sg10r6s01x1xthe194-4qpwdrk8jx-1c55weo-6eepkxpw9',
                    url: `ezopen://open.ys7.com/E74247772/1.rec?begin=20210408234637?begin=20210408234637&end=20210409001005`,
                    template: "security",
                    header: ['capturePicture'],
                    footer: [],
                    audio: 0,
                    width: width,
                    height: height
                });
                return player;
            },
            // 视频销毁
            pausemix(flvPlayer) {
                flvPlayer.stop();
                var list=document.getElementById(`playbackmonitor0`);
                list.removeChild(list.childNodes[0]);
                this.$set(this, 'flvPlayer', null);
            },
            monitorCheck(site) {
                this.isShow = true;
                // this.beginTime = this.common.formatTimestamp_min(site.startTime / 1000).replace(/-/g,"").replace(/ /g,"").replace(/:/g,"");
                // this.endTime = this.common.formatTimestamp_min(site.endTime / 1000).replace(/-/g,"").replace(/ /g,"").replace(/:/g,"");
                this.$nextTick(() => {
                    let player = this.initFlvPlayer();
                    this.player = player;
                })
            },
            closeMonitor() {
                this.isShow = false;
                this.monitorLoading = false;
                if(this.player) this.pausemix(this.player);
            },
            retry() {
                this.monitorLoading = true;
                let t = dayjs(new Date(this.beginTime).getTime() + (parseInt(this.currentTime) * 1000)).format();
                let index= t.lastIndexOf("\+");
                let index1 = this.endTime.lastIndexOf("\.");
                let beginTime = t.substring(0, index).replace(/-/g,"").replace(/:/g,"");
                let endTime = this.endTime.substring(0, index1).replace(/-/g,"").replace(/:/g,"");
                this.$nextTick(() => {
                    let centeredVideo = document.getElementById('playBack');
                    let player = this.initFlvPlayer(centeredVideo, `${this.channel_no}&start_time=${beginTime}&end_time=${endTime}`);
                    this.player = player;
                })
            }
        },
        beforeDestroy() {
            if(this.player != null) {
                this.player.stop();
            }
        }
    }
</script>
<style lang="scss" scoped>
    .container {
        width: 100%;
        display: flex;
        flex-direction: row;
        height: 100%;
        overflow: hidden;
        .play-back-tree {
            width: 300px;
            display: inline-block;
            vertical-align: top;
            height: 100%;
            overflow: auto;
            .video-tree-input {
                display: flex;
            }
            .monitor-ul {
                width: 100%;
                .monitor-item, .monitor-item-active {
                    width: 100%;
                    padding: 8px 24px;
                    box-sizing: border-box;
                    cursor: pointer;
                }
                .monitor-item-active {
                    color: #409EFF;
                }
            }
            ::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
                color: #409EFF;
            }
            .play-back-time {
                position: absolute;
                bottom: 0;
            }
        }
        .play-back-list {
            width: calc(100% - 300px);
            display: inline-block;
            padding-left: 20px;
            box-sizing: border-box;
            height: 100%;
            position: relative;
            .play-back-list-main {
                width: 100%;
                height: 100%;
                overflow: auto;
            }
            .select-input {
                display: flex;
                justify-content: flex-start;
                margin-bottom: 20px;
                flex-wrap: wrap;
                ::v-deep .el-input {
                    width: 230px;
                }
                ::v-deep .el-input__inner {
                    width: 230px;
                }
                .select-type {
                    display: inline-flex;
                    align-items: center;
                    margin: 0 16px;
                }
                .time-input {
                    margin-right: 16px;
                }
            }
            .play-back-ul {
                width: 100%;
                .play-back-li-date {
                    width: 100%;
                    font-size: 20px;
                    display: flex;
                    align-items: center;
                    line-height: 20px;
                    font-weight: bold;
                    &>i {
                        cursor: pointer;
                        margin-left: 16px;
                    }
                }
                .back-list {
                    width: 100%;
                    display: flex;
                    flex-wrap: wrap;
                    .back-li {
                        width: 150px;
                        display: inline-flex;
                        flex-direction: column;
                        margin: 20px 20px 0 0 ;
                        position: relative;
                        .el-icon-lock {
                            position: absolute;
                            padding: 8px;
                            cursor: pointer;
                            font-size: 22px;
                            left: 0;
                            top: 0;
                        }
                        .li-video {
                            width: 100%;
                            height: 200px;
                            background-color: #eee;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            cursor: pointer;
                            background: url('../../../assets/monitor_img.png') no-repeat;
                            .el-icon-video-play {
                                font-size: 36px;
                                color: #fff;
                            }
                        }
                        .video-time {
                            margin: 6px 0;
                        }
                    }
                }
            }
            ::v-deep .monitor {
                width: 100%;
                height: 100%;
                position: fixed;
                top: 0;
                left: 0;
                z-index: 10;
                background: #000;
                .el-icon-close {
                    position: absolute;
                    top: 55px;
                    right: 10px;
                    cursor: pointer;
                    color: #fff;
                    z-index: 20003;
                    font-size: 36px;
                }
                .monitor-video {
                    width: 100%;
                    height: 100%;
                }
                .monitor-error {
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%, -50%);
                    cursor: pointer;
                    color: #fff;
                }
                .video-controls {
                    width: 100%;
                    position: absolute;
                    bottom: 20px;
                    left: 0;
                    z-index: 10;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 0 24px;
                    box-sizing: border-box;
                    &>i {
                        color: #fff;
                        font-size: 32px;
                        cursor: pointer;
                        margin-right: 24px;
                    }
                    .currentTime {
                        color: #fff;
                        font-size: 16px;
                    }
                    .video-slider {
                        flex: 1;
                        margin: 0 24px;
                    }
                }
            }
            ::v-deep .monitor-hidden {
                width: 0;
                height: 0;
            }
        }
    }
    ::v-deep .vjs-fluid {
        height: 100%;
        padding-top: 0;
        overflow: hidden;
    }
    ::v-deep .video-js {
        width: 100%;
        height: 100%;
        overflow: hidden !important;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>
